package com.campus.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/9/24 15:54
 */
@Configuration
@PropertySource("classpath:application.properties")
@Slf4j
public class ResourceConfig {

    @Value("${spring.datasource.driver-class-name}")
    private String driver;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("root")
    private String username;

    @Value("cdw128898")
    private String password;

    @Value("${hikari.maximum-pool-size}")
    private int maximumPoolSize;

    @Value("${hikari.minimum-idle}")
    private int minimumIdle;

    @Value("${hikari.idle-timeout}")
    private long idleTimeout;

    @Value("${hikari.connection-timeout}")
    private long connectionTimeout;

    @Value("${hikari.max-lifetime}")
    private long maxLifetime;

    @Value("${hikari.pool-name}")
    private String poolName;

    /**
     * 配置连接池数据源
     * @return HikariDataSource 数据源
     */
    @Bean
    public DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(this.driver);
        dataSource.setJdbcUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);

        // 配置 HikariCP 参数
        dataSource.setMaximumPoolSize(maximumPoolSize);
        dataSource.setMinimumIdle(minimumIdle);
        dataSource.setIdleTimeout(idleTimeout);
        dataSource.setConnectionTimeout(connectionTimeout);
        dataSource.setMaxLifetime(maxLifetime);
        dataSource.setPoolName(poolName);

        log.info("HikariCP DataSource created with pool size: {}", maximumPoolSize);
        return dataSource;
    }

    /**
     * 配置 JdbcTemplate，直接从数据源获取连接
     * @param dataSource 数据源
     * @return JdbcTemplate
     */
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
